package org.footballmanager.pandafootball.system.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.annotation.SystemServiceLog;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.dao.FootClubDao;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.form.impl.FootClubSearchForm;
import org.footballmanager.pandafootball.system.mapper.FootClubMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FootClubServiceImpl extends RepeatServiceImpl<FootClub> implements FootClubService {
	@Autowired
	private FootClubDao footClubDao;
    @Autowired
    private FootClubMapper footClubMapper;
	@Autowired
	private FootSjService footSjService;
	@Autowired
	private FootRankService footRankService;
	@Autowired
	private FootTeamService footTeamService;
    @Autowired
    private FootUserPersonService footUserPersonService;
    @Autowired
    private FootTtService footTtService;
    @Autowired
    private FootQdService footQdService;
    @Autowired
    private FootUserService footUserService;

    /**
     * 更新非空字段
     * @param entity 参数
     * @param request 参数
     * @return 返回值
     */
    @Override
    @Transactional
    @SystemServiceLog(description = "更新俱乐部信息")
    public int updateNotNull(FootClub entity, HttpServletRequest request){
        FootUser user = footUserService.get(entity.getUserId());
        FootQd qd = footQdService.get(entity.getQdId());
        if(qd != null){
            entity.setQdId(qd.getId());
            footRankService.updateRankQdName(user.getId(), qd, request);
            footTtService.updateTtQdName(user.getId(), qd, request);
            //初始资金分配
            footTeamService.createZjTeamByUserId(entity.getUserId(), qd.getId(), qd.getQdmc(), request);
            //随机分配11个球员
            footUserPersonService.randomLow75(user.getId(), request);
        }
        return super.updateNotNull(entity, request);
    }

	/**
	 * 获取积分榜
	 * @param isGe24 是否大于24
	 */
	@Override
	public List<FootClub> getScoreboard(boolean isGe24, Long sjId) {
		FootClubSearchForm footClubSearchForm = new FootClubSearchForm();
		footClubSearchForm.setSj(sjId);
		if(isGe24){
			footClubSearchForm.setBscc(24);
		}
		return findall(footClubSearchForm);
	}

	/**
	 * 根据用户取俱乐部信息
	 */
	@Override
	public FootClub findByUserid(Long userId){
	    return footClubMapper.findByUserIdAndSjId(userId, footSjService.getSj());
	}

	@Override
	@Transactional
	public void reComputeRanking(HttpServletRequest request) {
		List<FootClub> list = this.getScoreboard(false, footSjService.getSj());
		if(null != list && !list.isEmpty()){
			int i = 1;
			for(FootClub fc: list){
				fc.setPm(i++);
				fc.setUpdateId((Long)request.getSession().getAttribute(Constants.USERID));
				fc.setUpdateTime(new Date());
				footClubDao.updateByPrimaryKeySelective(fc);
			}
		}
	}

	@Override
	public void addNewClubInfo(Long sj, HttpServletRequest request) {
		//获取所有用户，根据用户是否参加常规赛重新添加club信息到数据库中
        Example example = new Example(FootClub.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("sj", footSjService.getLastSj());
		List<FootClub> list = this.findall(example);
		if(list != null && !list.isEmpty()){
			for(FootClub club: list){
				FootClub newclub = new FootClub();
				BeanUtils.copyProperties(club, newclub);
				newclub.setBscc(0);
				newclub.setF(0);
				newclub.setJf(0);
				newclub.setJq(0);
				newclub.setJsq(0);
				newclub.setP(0);
				newclub.setPm(0);
				newclub.setS(0);
				newclub.setSl(0d);
				newclub.setSq(0);
				newclub.setSj(sj);
				//判断是否有重复数据
				if(!this.findRepeatData(newclub)){
					this.save(newclub, request);
				}

				FootTeam team = footTeamService.getTeamByUserid(newclub.getUserId());

				FootRank newrank = new FootRank();
				newrank.setSj(sj);
				newrank.setUserId(newclub.getUserId());
				newrank.setQdId(team.getQdId());
				//判断是否有重复数据
				if(!footRankService.findRepeatData(newrank)){
					footRankService.save(newrank, request);
				}
				
				FootTt newTt = new FootTt();
				newTt.setSj(sj);
				newTt.setUserId(newclub.getUserId());
				newTt.setQdId(team.getQdId());
				//判断是否有重复数据
				if(!footTtService.findRepeatData(newTt)){
					footTtService.save(newTt, request);
				}
			}
		}
	}

	private boolean findRepeatData(FootClub newclub) {
        Example example = new Example(FootClub.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("qdId", newclub.getQdId());
        criteria.andEqualTo(Constants.USERID, newclub.getUserId());
        criteria.andEqualTo("sj", newclub.getSj());
        List<FootClub> list = this.findall(example);
        return null != list && !list.isEmpty();
	}

	@Override
	public List<FootClub> getWinClubsBySj(int i, Long sj) {
        Example example = new Example(FootClub.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andGreaterThanOrEqualTo("bscc", 24);
        criteria.andEqualTo("sj", sj);
		if(i == 1){
		    example.orderBy("sq desc");
		}else if(i == 2){
            example.orderBy("jq desc");
		}else if(i == 3){
		    criteria.andGreaterThanOrEqualTo("bscc", 30);
		}else if(i == 4){
		    criteria.andGreaterThanOrEqualTo("sl", 0.2D);
		}else if(i == 5){
		    criteria.andGreaterThanOrEqualTo("sl", 0.5D);
		}else if(i == 6){
		    criteria.andGreaterThanOrEqualTo("sl", 0.8D);
		}else if(i == 7){
		    criteria.andGreaterThanOrEqualTo("jq", 50);
		}else if(i == 8){
		    criteria.andGreaterThanOrEqualTo("jq", 100);
		}
		return this.findall(example);
	}

	@Override
	public FootClub getTopClubBySj(int i) {
		int position = i - 1;
		List<FootClub> list = this.getScoreboard(true, footSjService.getSj());
		if(null != list && (list.size() > position)){
			return list.get(position);
		}
		return null;
	}

	@Override
	public Serializable saveNewClub(FootUser user, HttpServletRequest request) {
		FootClub fc = new FootClub();
		fc.setQdId(user.getQdId());
		fc.setClsj(new Date());
		fc.setUserId(user.getId());
		fc.setSj(footSjService.getSj());
		return this.save(fc, request);
	}

	@Override
	public List<FootClub> getClubsByUseridandSj(Long userId, Long sj) {
        Example example = new Example(FootClub.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("sj", sj);
        criteria.andEqualTo(Constants.USERID, userId);
		return this.findall(example);
	}

	@Override
	public Boolean findNumByUserId(Long userId) {
		List<FootClub> list = this.getScoreboard(false, footSjService.getSj());
		if(list != null && !list.isEmpty()){
			int j = 0;
			for(int i = 0; i < list.size(); i++){
				FootClub club = list.get(i);
				if(club.getUserId().equals(userId)){
					j = i;
				}
			}
			return j < 16;
		}
		return false;
	}

	@Override
	public List<FootClub> findTopClub(Long sjid, Integer top, Integer buttom) {
		Example example = new Example(FootClub.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("sj", sjid);
		criteria.andGreaterThanOrEqualTo("pm", top);
		criteria.andLessThanOrEqualTo("pm", buttom);
		example.orderBy("pm asc");
		return this.findall(example);
	}

    /**
     * 翻页方法
     *
     * @param footClubSearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootClub> findall(FootClubSearchForm footClubSearchForm) {
        return footClubMapper.findall(footClubSearchForm);
    }

	/**
	 * 根据主键获取记录
	 * @param id 主键
	 * @return 记录
	 */
	@Override
	public FootClub get(Serializable id) {
		return footClubMapper.findById(id);
	}

    /**
     * 查询
     *
     * @param entityname         实体类名
     * @param map                参数
     * @param footClubSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootClubSearchForm footClubSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footClubSearchForm);
        List<FootClub> list = this.findall(footClubSearchForm);
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 更改球队设置
     *
     * @param footClub 俱乐部实体类
     * @param request  请求
     */
    @Override
    public void changeQd(FootClub footClub, HttpServletRequest request) {
        FootClub fc = footClubDao.selectByPrimaryKey(footClub.getId());
        //换队壳
        FootUser user = footUserService.get(fc.getUserId());
        FootTeam team = footTeamService.getTeamByUserid(user.getId());
        FootRank rank = footRankService.findByUserid(user.getId());
        FootQd newqd = footQdService.get(footClub.getQdId());
        if(team != null){
            team.setId(newqd.getId());
            rank.setQdId(newqd.getId());
            footRankService.updateNotNull(rank, request);
            footTeamService.updateNotNull(team, request);
        }
    }
}
